<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现购物车结算功能代码</title>
    <link rel="stylesheet" href="../css/style.css" />
    <style>
        .goods span {
            /* 2.多行文本溢出隐藏 */
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            /*设置对齐模式*/
            -webkit-line-clamp: 2;
            /*设置多行的行数，示例为2行*/
        }
    </style>
</head>

<body>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/2.jpg" alt="" /><span>Canon/佳能 PowerShot SX50 HS</span></td>
                    <td class="price">3888.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">3888.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/3.jpg" alt="" /><span>Sony/索尼 DSC-WX300</span></td>
                    <td class="price">1428.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">1428.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/4.jpg" alt="" /><span>Fujifilm/富士 instax mini 25</span></td>
                    <td class="price">640.60</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">640.60</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">

            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/1.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>
    // ajax请求数据 => 渲染购物车

    console.log("代码开始");

    var tbody = document.querySelector("#cartTable tbody");

    var xhr = new XMLHttpRequest(); // 0

    xhr.open("get", "../data/shoppingCar.json", true);  // 1

    xhr.send(); // 1

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log("请求成功");
            var result = xhr.responseText;
            result = JSON.parse(result);
            console.log(result);

            var { list } = result;

            var html = "";
            list.forEach(({ goodsName, goodsImg, goodsPrice, buyNum }) => {
                // ES6 模版字符串和插值语句(可以拼接变量 / 表达式 / 方法)
                html += `<tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsName}</span>
                    </td>
                    <td class="price">${(goodsPrice * 1).toFixed(2)}</td>
                    <td class="count">
                        <span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(goodsPrice * buyNum).toFixed(2)}</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>`
            })
            // 动态生成之前
            tbody.innerHTML = html;  // 动态生成
            // 动态生成之后
        }
    }


    // ajax动态生成和绑定事件的问题:
    // (1) ajax请求是异步的 => 等服务端(后端)返回数据时,商品动态生成之前,同步代码早已经执行完毕 => 问题: 购物车中的商品还未渲染,但是事件绑定就已经执行了  => 但是由于商品还未生成,导致获取的元素(单选 加 减 单删)都是[]

    // 简单来说:  同步代码先执行, ajax事件中的代码后执行(此时才会动态生成)  => 绑定事件发生在商品动态生成之前, (只有存在的元素才能绑定事件 => checkAll,deleteAll  ,单选 加 减 单删还未生成无法绑定事件 ) 

    // 解决方法:
    // (1) 等ajax数据请求成功,且商品动态生成之后再获取元素和绑定事件  => 老赖行为
    // (2) 利用事件委托,将子元素的事件委托给父元素(页面中已存在的 document),由父元素代为执行, 该获取的元素还是要获取


    // 注意: 事件委托,只是将子元素的事件委托给父元素,由父元素代为执行, 该获取的元素还是要获取

    var catbox = document.getElementsByClassName("catbox")[0];
    var checkAll = document.getElementsByClassName("check-all")[0];
    var checkOneList = document.getElementsByClassName("check-one");
    var selectedTotal = document.getElementById("selectedTotal");
    var priceTotal = document.getElementById("priceTotal");


    catbox.addEventListener("click", entrustHandler);

    function entrustHandler(e) {
        // this => 绑定事件的元素 catbox
        // console.log(this,e);
        e = e || window.event;
        var target = e.target;  // 触发事件的元素(事件源)
        console.log(target);

        if (target.classList.contains("check-all")) {
            checkAllHandler(target);
            getTotal();
        } else if (target.classList.contains("check-one")) {
            isAllChecked();
            getTotal();
        } else if (target.className == "add") {
            addHandler(target);
            getTotal();
        } else if (target.className == "reduce") {
            reduceHandler(target)
            getTotal();
        } else if (target.className == "delete") {
            deleteOneHandler(target)
            isAllChecked();  // 删除完毕 => 判断是否反选
            getTotal();
        } else if (target.id == "deleteAll") {
            deleteAllHandler();
            isAllChecked();
            getTotal();
        }

    }


    function checkAllHandler(target) {
        var status = target.checked;
        for (var i = 0; i < checkOneList.length; i++) {
            var checkOne = checkOneList[i];
            checkOne.checked = status;
        }
    }



    function isAllChecked() { // 判断是否反选

        var flag = true; // 假设全都被选中
        for (var j = 0; j < checkOneList.length; j++) {
            var item = checkOneList[j];
            if (!item.checked) {
                flag = false;
                break;
            }
        }

        // 判断是否有商品  => 有商品就是用flag,没有商品 checkAll.checked = false;
        checkAll.checked = checkOneList.length == 0 ? false : flag;
    }

    function addHandler(target) {
        //a. 输入框  数量 加一 
        var countInput = target.previousElementSibling;
        var num = countInput.value;
        num++;
        countInput.value = num;
        // countInput.value ++;
        console.log(num);

        //b. 小计更新  =  单价*数量
        var priceTd = target.parentElement.previousElementSibling;
        var subtotalTd = target.parentElement.nextElementSibling;
        console.log(priceTd, subtotalTd);

        var price = priceTd.textContent;
        subtotalTd.textContent = (price * num).toFixed(2);

        // c  减号按钮的 “-”  出现
        var reduce = countInput.previousElementSibling;
        reduce.textContent = "-";
    }

    function reduceHandler(target) {
        // a. 输入框  数量 减一 
        var countInput = next(target);
        var num = countInput.value;
        // c. 减之前判断 如果商品数量为1,不能减
        if (num == 1) {
            alert("亲,不能再少了!");
            return false;  // 阻止函数继续向后执行
        }

        num--;

        // d. 减之后判断, 如果商品数量为1 (2切换为1), "-"消失
        if (num == 1) {
            target.textContent = "";
        }


        countInput.value = num;

        // b. 小计更新  =  单价*数量
        var priceTd = prev(parent(target));
        var subtotalTd = next(parent(target));
        console.log(priceTd, subtotalTd);

        var price = priceTd.textContent;
        subtotalTd.textContent = (price * num).toFixed(2);
    }

    function deleteOneHandler(target) {
        // console.log(this, del, i);
        var bool = confirm("是否删除该商品");
        // console.log(bool);
        if (bool) {
            var parentTr = parent(parent(target));
            parentTr.remove();
        }
    }

    function deleteAllHandler() {
        for (var j = 0; j < checkOneList.length; j++) {
            var checkOne = checkOneList[j];
            if (checkOne.checked) {
                var tr = parent(parent(checkOne));
                tr.remove();
                j--;
            }
        }
    }

    function getTotal() {
        var sum = 0;
        var allPrice = 0;

        for (var j = 0; j < checkOneList.length; j++) {
            var item = checkOneList[j];  // 每一个单选
            if (item.checked) {
                var tr = parent(parent(item));
                var countInput = tr.getElementsByClassName("count-input")[0];
                var subtotalTd = tr.getElementsByClassName("subtotal")[0];

                var num = countInput.value * 1;
                var subtotal = subtotalTd.textContent * 1;

                sum += num;
                allPrice += subtotal;

            }
        }

        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }

    function parent(ele) {
        return ele.parentElement;
    }

    function prev(ele) {
        return ele.previousElementSibling;
    }

    function next(ele) {
        return ele.nextElementSibling;
    }










    console.log("代码结束");
</script>

</html>